<template>
  <div style="min-height: 500px;" v-loading="loading" element-loading-background="rgba(255, 255, 255 0.8)">
    <div class="ja-container" id="jobappform" v-if="saveState !== 'SUCCESS'">
      <p class="prompt-text">1. 本科、大专及以上学历申报认定（包括在职教育）。要求：本科学历毕业后工作时间满1年、大专学历毕业后工作时间满3年可申报。</p>
      <p class="prompt-text">2. 中专学历申报评审。要求：毕业后工作时间满5年可申报。</p>
      <p class="prompt-text">3. 非测绘专业、高中及以下学历申报破格。要求：毕业后工作时间满6年可申报。</p>
      <el-button type="success" v-if="row && row.expertResult === 'SUCCESS'" icon="el-icon-download" class="fr" style="font-size: 14px;padding: 8px;" @click="downloadFile()">职称申请表</el-button>
      <div class="flex-row " style="margin-bottom: 28px;">
        <div class="duigou-con ">
          <el-radio v-model="declareType" label="HOLD" border>认定</el-radio>
          <span class="duigou" v-show="declareType === 'HOLD'"><li class="duigou-inner el-icon-check"></li></span>
        </div>
        <div class="duigou-con ">
          <el-radio v-model="declareType" label="REVIEW" border>评审</el-radio>
          <span class="duigou" v-show="declareType === 'REVIEW'"><li class="duigou-inner el-icon-check"></li></span>
        </div>
        <div class="duigou-con ">
          <el-radio v-model="declareType" label="UNUSUAL" border>破格</el-radio>
          <span class="duigou" v-show="declareType === 'UNUSUAL'"><li class="duigou-inner el-icon-check"></li></span>
        </div>
      </div>
      <time-line>
        <el-collapse v-model="activeName" accordion>
          <!-- <timeline-item :color="activeName === '1' ? 'green' : '#BAC1B0'">
            <el-collapse-item title="公司信息" name="1">
              <template slot="title">公司信息&nbsp;&nbsp;&nbsp;<i class="header-icon el-icon-edit" v-show="activeName !== '1'"></i></template>
              <company-info :companyinfo.sync="companyinfo" ref="companyinfo"></company-info>
            </el-collapse-item>
          </timeline-item> -->
          <timeline-item :color="activeName === '2' ? 'green' : '#BAC1B0'">
            <el-collapse-item title="个人信息" name="2">
              <template slot="title">个人信息&nbsp;&nbsp;&nbsp;<i class="header-icon el-icon-edit" v-show="activeName !== '2'"></i></template>
              <person-info :personinfo.sync="personinfo" ref="personinfo"></person-info>
            </el-collapse-item>
          </timeline-item>
          <timeline-item :color="activeName === '3' ? 'green' : '#BAC1B0'">
            <el-collapse-item title="学历学位" name="3">
              <template slot="title">学历学位&nbsp;&nbsp;&nbsp;<i class="header-icon el-icon-edit" v-show="activeName !== '3'"></i></template>
              <education-info :educationinfo.sync="educationinfo" ref="educationinfo" :declare-type="declareType"></education-info>
            </el-collapse-item>
          </timeline-item>
          <timeline-item :color="activeName === '4' ? 'green' : '#BAC1B0'">
            <el-collapse-item title="其他信息" name="4">
              <template slot="title">其他信息&nbsp;&nbsp;&nbsp;<i class="header-icon el-icon-edit" v-show="activeName !== '4'"></i></template>
              <other-info :otherinfo.sync="otherinfo" ref="otherinfo"></other-info>
            </el-collapse-item>
          </timeline-item>
          <timeline-item :color="activeName === '5' ? 'green' : '#BAC1B0'" v-if="declareType === 'UNUSUAL'">
            <el-collapse-item title="破格申请材料" name="5">
              <template slot="title">破格申请材料&nbsp;&nbsp;&nbsp;<i class="header-icon el-icon-edit" v-show="activeName !== '5'"></i></template>
              <badapp-material :badappmaterial.sync="badappmaterial" ref="badappmaterial"></badapp-material>
            </el-collapse-item>
          </timeline-item>
        </el-collapse>
      </time-line>
      <div class="tc">
        <el-button type="success width-200" plain round @click="goBack()">返回</el-button>
        <el-button type="success width-200" round @click="confirm('SAVE')"
        v-if="!row || (row.saveSubmit === 'SAVE' || (row.verifyStatus === 'FAIL' && !row.expertResult) )">保存</el-button>
        <!-- <el-button type="success width-200" plain round @click="confirm('ADD')" v-if="!row">新增</el-button> -->
      </div>
    </div>

    <div class="va-container flex-column-center promp-msg" v-if="saveState === 'SUCCESS'">
      <img src="../../assets/shenhetongguo.jpg" alt="" style="margin-top: 100px;">
      <h2>保存成功</h2>
      <!-- 客户要求不可以再新增了 -->
      <el-button type="success" class="width-200 " round @click="addNew()" v-if="!row && $store.state.isJob">
        新增申请
      </el-button>
      <el-button type="success" class="width-200 mt-2" round @click="corssBack()">
        返回列表
      </el-button>

    </div>
  </div>
</template>

<script>
import axios from 'axios'
import eventBus from '../../plugins/eventbus.js'

import BadappMaterial from './BadappMaterial'
// import CompanyInfo from './CompanyInfo'
import EducationInfo from './EducationInfo'
import OtherInfo from './OtherInfo'
import PersonInfo from './PersonInfo'

let v = async function (self) {
  let result2 = await self.$refs.personinfo.validate()
  if (!result2) {
    self.activeName = '2'
    return false
  }
  let result3 = await self.$refs.educationinfo.validate()
  if (!result3 || !(self.educationinfo.chsi.length > 0 || self.declareType !== 'HOLD')) {
    self.activeName = '3'
    return false
  }
  let result4 = await self.$refs.otherinfo.validate()
  if (!result4 || self.otherinfo.attachment.length === 0) {
    if (self.otherinfo.attachment.length === 0) {
      self.$message({
        message: '请上传其他信息中的附件',
        type: 'warning'
      })
    }
    self.activeName = '4'
    return false
  }
  if (self.declareType === 'UNUSUAL') {
    let result5 = await self.$refs.badappmaterial.validate()
    if (!result5) {
      self.activeName = '5'
      return false
    }
  }
  return true
}

  export default {
    components: {
      // CompanyInfo,
      BadappMaterial,
      EducationInfo,
      OtherInfo,
      PersonInfo
    },
    title: '初级职称申请',
    name: 'job-app-form',
    data () {
      return {
        loading: false,
        saveState: 'WAIT',
        activeName: '1',
        declareType: 'HOLD',
        // companyinfo: {
        //   companyName: '',
        //   department: '',
        //   contactsName: '',
        //   contactsPhone: ''
        // },
        personinfo: {
          username: '',
          sex: '1',
          profession: '',
          position: '',
          birthday: '',
          toWorkTime: '',
          photo: ''
        },
        educationinfo: {
          fullTimeEducation: '',
          fteSchoolProfession: '',
          workEducation: '',
          weSchoolProfession: '',
          certificateNo: '',
          certificateScanningCopy: [],
          chsi: []
        },
        otherinfo: {
          dispositionAndReward: '',
          foreignLanguageAbility: '',
          workExperience: '',
          expertiseAchievement: '',
          businessAdvice: '',
          attachment: ''
        },
        badappmaterial: {
          workYears: '',
          unusualReport: '',
          mainAchievement: '',
          companyAdvice: '',
          reviewDepartmentAdvice: '',
          // unusualAttachment: ''
        },
        badappmaterialnull: {
          workYears: null,
          unusualReport: null,
          mainAchievement: null,
          companyAdvice: null,
          reviewDepartmentAdvice: null,
          // unusualAttachment: null
        },
        row: null
      }
    },
    methods: {
      confirm (status) {
        v(this).then(result => {
          if (result) {
            this.loading = true
            let obj
            if (this.declareType === 'UNUSUAL') {
              obj = Object.assign({}, this.row, this.personinfo, this.educationinfo, this.otherinfo, this.badappmaterial)
            } else {
              obj = Object.assign({}, this.row, this.personinfo, this.educationinfo, this.otherinfo, this.badappmaterialnull)
            }
            // 如果是全日制教育，将在职信息清空，否则清空全日制数据
            if (this.$refs.educationinfo.education === 'FULL') {
              obj.workEducation = ''
              obj.weSchoolProfession = ''
            } else {
              obj.fullTimeEducation = ''
              obj.fteSchoolProfession = ''
            }
            // obj.userId  = getuser().data.user.userId
            obj.userId = this.$store.state.user.user.user.userId
            obj.declareType = this.declareType
            obj.saveSubmit = 'SAVE'
            // 学历附件，必填，不用判断是否为空
            if (typeof obj.certificateScanningCopy === 'object' || typeof obj.chsi === 'object') {
              obj.certificateScanningCopy = JSON.stringify([
                ...obj.certificateScanningCopy.map(item => {
                  item.type = 'certificateScanningCopy'
                  return item
                }),
                ...obj.chsi.map(item => {
                  item.type = 'chsi'
                  return item
                })
              ])
            }
            // 破格中的附件
            // if (this.declareType === 'UNUSUAL') {
            //   if (obj.unusualAttachment.length === 0) {
            //     obj.unusualAttachment = null
            //   } else {
            //     if (typeof obj.unusualAttachment === 'object') {
            //       obj.unusualAttachment = JSON.stringify(obj.unusualAttachment)
            //     }
            //   }
            // }
            // 其他信息中的附件
            if (obj.attachment.length === 0) {
              obj.attachment = null
            } else {
              if (typeof obj.attachment === 'object') {
                obj.attachment = JSON.stringify(obj.attachment)
              }
            }
            axios.post('/mscs/review/addProfessionalTitleReviewInfo', obj).then((res) => {
              if (res.data.code === 1) {
                this.saveState = 'SUCCESS'
                if (status === 'ADD') {
                  this.cleartData()
                  this.$message({
                    message: '保存成功，继续添加',
                    type: 'success'
                  })
                  this.activeName = '1'
                } else {
                  // eventBus.$emit('confirm-success')
                  // 提交成功，将公司信息存储起来，以便后面在输入
                  // this.$router.go(-1)
                }

              } else {
                this.$message({
                  showClose: true,
                  message: `错误信息：${res.data.data[0].errorMsg}`,
                  type: 'error'
                })
              }
            }).catch((error) => {
              this.$catchError(error)
            }).finally(() => {
              this.loading = false
            })

          } else {
            this.$alert('保存失败，信息填写不完整或不正确，其中标注红色为未填写或填写错误', {
              confirmButtonText: '确定',
            })
          }
        })
      },
      // 新增人员，先保存后清空，重新增加
      addNew () {
        // 调用cleartData即可
        this.cleartData()
        this.activeName = '1'
        this.saveState = 'WAIT'
      },
      corssBack (flag) {
        eventBus.$emit('confirm-success')
        this.$router.go(-1)
        setTimeout(() => {
          this.saveState = 'WAIT'
        }, 100)
      },
      setData (row) {

        this.declareType = row.declareType

        // this.companyinfo.companyName = row.companyName
        // this.companyinfo.department = row.department
        //
        // this.companyinfo.contactsName = row.contactsName
        // this.companyinfo.contactsPhone = row.contactsPhone

        this.personinfo.username = row.username
        this.personinfo.sex = row.sex.toString()
        this.personinfo.birthday = row.birthday
        this.personinfo.toWorkTime = row.toWorkTime
        this.personinfo.photo = row.photo
        this.personinfo.profession = row.profession
        this.personinfo.position = row.position

        this.educationinfo.fullTimeEducation = row.fullTimeEducation
        this.educationinfo.fteSchoolProfession = row.fteSchoolProfession
        this.educationinfo.workEducation = row.workEducation
        this.educationinfo.weSchoolProfession = row.weSchoolProfession
        this.educationinfo.certificateScanningCopy = row.certificateScanningCopy
        this.educationinfo.certificateNo = row.certificateNo

        this.otherinfo.dispositionAndReward = row.dispositionAndReward
        this.otherinfo.foreignLanguageAbility = row.foreignLanguageAbility
        this.otherinfo.workExperience = row.workExperience
        this.otherinfo.expertiseAchievement = row.expertiseAchievement
        this.otherinfo.expertiseAchievement = row.expertiseAchievement
        this.otherinfo.businessAdvice = row.businessAdvice
        this.otherinfo.attachment = row.attachment

        this.badappmaterial.workYears = row.workYears || ''
        this.badappmaterial.unusualReport = row.unusualReport || ''
        this.badappmaterial.mainAchievement = row.mainAchievement || ''
        this.badappmaterial.companyAdvice = row.companyAdvice || ''
        this.badappmaterial.reviewDepartmentAdvice = row.reviewDepartmentAdvice || ''
        // this.badappmaterial.unusualAttachment = row.unusualAttachment
        this.row = row
      },
      cleartData () {
        this.declareType = 'HOLD'

        this.personinfo.username = ''
        this.personinfo.sex = '1'
        this.personinfo.birthday = ''
        this.personinfo.toWorkTime = ''
        this.personinfo.photo = ''
        this.personinfo.profession = ''
        this.personinfo.position = ''

        this.educationinfo.fullTimeEducation = ''
        this.educationinfo.fteSchoolProfession = ''
        this.educationinfo.workEducation = ''
        this.educationinfo.weSchoolProfession = ''
        this.educationinfo.certificateNo = ''
        this.educationinfo.certificateScanningCopy = ''
        this.educationinfo.chsi = []

        this.otherinfo.dispositionAndReward = ''
        this.otherinfo.foreignLanguageAbility = ''
        this.otherinfo.workExperience = ''
        this.otherinfo.expertiseAchievement = ''
        this.otherinfo.expertiseAchievement = ''
        this.otherinfo.businessAdvice = ''
        this.otherinfo.attachment = ''

        this.badappmaterial.workYears = ''
        this.badappmaterial.unusualReport = ''
        this.badappmaterial.mainAchievement = ''
        this.badappmaterial.companyAdvice = ''
        this.badappmaterial.reviewDepartmentAdvice = ''
        // this.badappmaterial.unusualAttachment = ''
        this.row = null
        if (this.$refs.educationinfo) {
          this.$refs.educationinfo.clearFiles()
        }
        if (this.$refs.otherinfo) {
          this.$refs.otherinfo.clearFiles()
        }
        // if (this.$refs.badappmaterial) {
        //   this.$refs.badappmaterial.clearFiles()
        // }
        this.fileList = []
      },
      goBack () {
        // this.$router.push({name: 'job'})
        this.$router.go(-1)
      },
      downloadFile () {
        v(this).then(result => {
          if (result) {
            let obj
            if (this.declareType === 'UNUSUAL') {
              obj = Object.assign({}, this.row, this.personinfo, this.educationinfo, this.otherinfo, this.badappmaterial)
            } else {
              obj = Object.assign({}, this.row, this.personinfo, this.educationinfo, this.otherinfo, this.badappmaterialnull)
            }
            let filePath = 'http://cdn.i-tudou.com/document/positional-titles.xlsx'
            if (this.declareType === 'UNUSUAL') {// 破格
              filePath = 'http://cdn.i-tudou.com/document/positional-titles-unusual.xlsx'
            }
            let params = {
              filePath: filePath,
              reviewData: JSON.stringify(obj)
            }
            axios.post('/mscs/review/exportProfessnalReviewExcel', this.$paramsConvert(params),{responseType: 'arraybuffer'}).then(res => {
              const content = res.data
              const blob = new Blob([content], {type: "application/vnd.ms-excel"})
              const fileName = '职称申请表.xlsx'
              if ('download' in document.createElement('a')) { // 非IE下载
                const elink = document.createElement('a')
                elink.download = fileName
                elink.style.display = 'none'
                elink.href = URL.createObjectURL(blob)
                document.body.appendChild(elink)
                elink.click()
                URL.revokeObjectURL(elink.href) // 释放URL 对象
                document.body.removeChild(elink)
                // let objectUrl = URL.createObjectURL(blob)
                // window.location.href = objectUrl
              } else { // IE10+下载
                navigator.msSaveBlob(blob, fileName)
              }
            }).catch(error => {
              this.$catchError(error)
            })

          }
        })
      }
    },
    beforeRouteEnter (to, from, next) {
     next(vm => {
       let params = to.params
       if (!from.name) {
         params = vm.$lsget('routerToParams')
       }
       if (Object.keys(params).length > 10) {
         vm.setData(params)
       } else {
         vm.cleartData()
       }
     })
    },
  }
</script>
<style>
  #jobappform {
    padding-top: 50px;
  }
  #jobappform .duigou-con {
    margin-right: 12px;
  }
  #jobappform .el-collapse-item__header {
    font-size: 18px;
    color: #3b541c;
    height: auto;
    line-height: normal;
    border-bottom: none;
  }
  /* 去掉展开和默认的底部边框 */
  #jobappform .el-collapse {
    border: none;
  }
  #jobappform .el-collapse-item__wrap {
    border-bottom: none;
  }
  /* 一下两个是让标识圈偏离整体文档 */
  #jobappform .timeline {
    margin-left: -50px;
  }
  #jobappform .timeline-item-content {
    padding-left: 50px;
  }
  /* 清除右边展开的标识箭头 */
  #jobappform .el-collapse-item__arrow:before {
    content: "";
  }
  /* 让标题文字和右边图标对其 */
  #jobappform .el-collapse-item:last-child {
    margin-top: -2px;
  }
  /* 修改展开想的title */
  #jobappform .is-active {
    font-size: 20px;
    color: #3b541c;
  }
  #jobappform .el-icon-edit:before {
    background: #94C05A;
    border-radius: 50%;
    color: #FFFFFF;
    padding: 3px;
    font-size: 15px;
  }
  /* 暂未查明输入框绿线为什么会差3px */
  /* #jobappform .material-textfield label::after {
    top: -2px;
  } */
  /* 去掉折叠下方的间距，防止表单出现滚动 */
  #jobappform .el-collapse-item__content {
    padding-bottom: 0;
  }
</style>
